<?php

namespace MoChat\App\Sales\Action\Client;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Sales\Contract\SalesTaskContract;
use MoChat\App\Sales\Contract\WorkDepartmentContract;
use MoChat\App\Sales\Model\SalesClientTask;
use MoChat\App\Sales\Model\SalesTask;
use MoChat\App\Sales\Model\WorkDepartment;
use MoChat\App\Sales\Service\WorkDepartmentService;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Shared\Date;

/**
 * 销售任务导入
 * @Controller
 */
class Export extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var SalesTaskContract
     */
    protected $salesTaskService;

    /**
     * @Inject
     * @var WorkDepartmentContract
     */
    protected $workDepartmentService;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     * })
     * @RequestMapping(path="/dashboard/salesClient/export", methods="POST")
     */
    public function handle()
    {
        $user = user();
        // 判断用户绑定企业信息
        if (!isset($user['corpIds']) || count($user['corpIds']) !== 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        $file = $this->request->file('file');
        if (!$file){
            throw new CommonException(ErrorCode::INVALID_PARAMS, '请上传excel文件');
        }
        $extension = $file->getExtension();
        if (!in_array(strtolower($extension), ['xlsx', 'xls'])) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, 'excel文件格式错误');
        }
        $tmpName = $file->getRealPath();
        if (is_uploaded_file($tmpName)) {
            // 有Xls和Xlsx格式两种
            $objReader = IOFactory::createReader('Xlsx');

            $filename = $tmpName;
            $objPHPExcel = $objReader->load($filename);  //$filename可以是上传的表格，或者是指定的表格
            $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
            $highestRow = $sheet->getHighestRow();       // 取得总行数
            // $highestColumn = $sheet->getHighestColumn();   // 取得总列数

            //定义$usersExits，循环表格的时候，找出已存在的用户。
            $data = [];
            //循环读取excel表格，整合成数组。如果是不指定key的二维，就用$data[i][j]表示。
            for ($j = 2; $j <= $highestRow; $j++) {
                $deptName = $objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue();
                $deptId = WorkDepartment::where('name', trim($deptName))->value('id');
                if (!$deptId){
                    throw new CommonException(ErrorCode::INVALID_PARAMS, 'excel第'.$j.'行部门名称不存在');
                }
                $data[$j - 2] = [
                    'corp_id' => $user['corpIds'][0],
                    'work_department_id' => $deptId ?: 0,
                    'name' =>$objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue(),
                    'start_time' => date('Y-m-d H:i:s', Date::excelToTimestamp($objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue(), 'PRC')),
                    'end_time' => date('Y-m-d H:i:s', Date::excelToTimestamp($objPHPExcel->getActiveSheet()->getCell("D" . $j)->getValue(), 'PRC')),
                    'sales_task' => (float)$objPHPExcel->getActiveSheet()->getCell("E" . $j)->getValue(),
                    'remark' => $objPHPExcel->getActiveSheet()->getCell("F" . $j)->getValue(),
                    'created_at' => date('Y-m-d H:i:s'),
                ];

            }
            if (count($data)) {
                if (!SalesClientTask::insert($data)) {
                    throw new CommonException(ErrorCode::INVALID_PARAMS, '导入失败');
                }
            }
        }
        return [];
    }

    /**
     * 验证规则.
     */
    protected function rules(): array
    {
        return [
            'file' => 'required',
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    protected function messages(): array
    {
        return [
            'file.required' => '请上传excel文件',
        ];
    }
}